




package com.yinhai.ta404.module.security.cas.filter;

import com.yinhai.ta404.core.exception.AppException;
import com.yinhai.ta404.core.utils.StringUtils;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

public class TaCasLogoutFilter extends LogoutFilter {
    private static final Logger logger = LoggerFactory.getLogger(TaCasLogoutFilter.class);
    private String ssoLogoutTargetUrl;

    public TaCasLogoutFilter(String ssoLogoutTargetUrl, LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) {
        super(logoutSuccessHandler, handlers);
        this.ssoLogoutTargetUrl = ssoLogoutTargetUrl;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        if (this.requiresLogout((HttpServletRequest)req, (HttpServletResponse)res)) {
            if (StringUtils.isBlank(this.ssoLogoutTargetUrl) && StringUtils.isBlank(req.getParameter("frontUrl"))) {
                throw new AppException("退出参数缺失！");
            }

            super.doFilter(req, res, chain);
        } else {
            long start = System.currentTimeMillis();
            try {
                chain.doFilter(req, res);
            } catch (IOException e) {
                logger.error("请求IO异常，message：{}，请求路径：{}，处理耗时：{}毫秒", e.getMessage(), ((HttpServletRequest) req).getRequestURL(), System.currentTimeMillis() - start);
                logger.error("请求IO异常", e);
                throw e;
            }
        }

    }
}
